# -*- coding: utf-8 -*-
# @Time    : 2020/5/11 17:11
# @Author  : suhong
# @File    : fateadm_code.py
# @Software: PyCharm

"""
此次下载的最新时间
2020-05-09 14:16:06
1589004966
"""

import requests
import time
import hashlib
import json
from re_common.baselibrary.utils.basedir import BaseDir
from re_common.baselibrary.utils.basefile import BaseFile

h = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36',
    'Cookie': 'UM_distinctid=170e1db014e408-010f1de5c45342-c343162-15f900-170e1db014f47c; Hm_lvt_d879e12e7fda125abfff5f39d9ace520=1589187405; PHPSESSID=16faea3ac0d7d687b3eb9a5ec5d6e48b; fa_user_name=xujiang; fa_cookie_token=5ace7745be355d5b44f5b1363790e8fc; CNZZDATA1262416940=1188440500-1584335543-https%253A%252F%252Fwww.baidu.com%252F%7C1589244940; Hm_lpvt_d879e12e7fda125abfff5f39d9ace520=1589245180',
}
base_img_url = 'http://im.fateadm.com:8081/img/'
account = 'xujiang5@163.com'
page = 0
def down():
    global page
    while True:
        try:
            millis = int(round(time.time() * 1000))
            millis_10 = str(millis)[:10]

            url_get = 'http://www.fateadm.com/config/rsa.php?_{}'.format(millis)
            r = requests.get(url_get,headers=h)
            md5_rsa_str_sign = eval(r.text)['md5_rsa_str_sign']

            # 处理post里的sign
            before_str = account + str(millis_10) + md5_rsa_str_sign
            sign = hashlib.md5(before_str.encode(encoding='utf-8')).hexdigest()

            url_post = 'http://www.fateadm.com/php/reg_log.php?type=GetDetail'
            data = {
                'sign': sign,
                'startidx': str(page*10),
                'row_num': '11',
                'account': account,
                'timestamp': millis_10
            }
            r = requests.post(url_post,data=data,headers=h)
            json_data = json.loads(r.text)
            msg = json_data['msg']

            result = json_data['result']
            print(msg)
            print(result)
            if msg != 'success':
                print(page)
                time.sleep(100)
            for info in result:
                pred_reslt = info['pred_reslt']
                # 以code来头字母创建文件夹
                filepath = r'E:\更新数据\code'
                BaseDir.create_dir(filepath)
                filename = "{}/{}.jpg".format(filepath,pred_reslt)
                if BaseDir.is_dir_exists(filename):
                    print(pred_reslt+'已存在')
                    continue
                print(pred_reslt)
                img_url = base_img_url + info['order_id'] + '.jpg'
                r_img = requests.get(img_url)
                BaseFile.single_write_wb_file(r_img.content,filename)

            print("当前page:{}".format(page+1))
            page += 1
        except Exception as e:
            print("当前page:{}".format(page + 1))
            print(e)
            break


down()